<?php
/**
 * Created by 1971599474@qq.com
 * User: zhixuan
 * Date: 2020/1/17
 * Time: 15:21
 */

namespace app\index\controller;


use app\common\controller\BaseController;
use  app\common\model\Member;
use think\facade\Db;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use app\common\model\Member as MemberModel;
use think\facade\Session;

class Login extends BaseController
{

    public $return = ['code'=>300,'msg'=>'','data'=>[]];
    public function login(){
        if ($this->request->isAjax()) {
            $return = $this->return;
            $tel = input("param.tel", 0);
            if (empty($tel)) {
                $return['msg'] = '手机号不能为空';
                return json($return);
            }

            if (!check_tel($tel)) {
                $return['msg'] = '手机号格式不正确';
                return json($return);
            }
            $has = Member::getOne(['tel'=>$tel]);

            if (empty($has)) {
                $return['msg'] = '该手机号用户不存在';
                return json($return);
            }

            $password = input('password');
            if (!$password) {
                $return['msg'] = '密码不能为空';
                return json($return);
            }

            if ($has['password'] !== md5(md5($password))) {
                $return['msg'] = '密码不正确';
                return json($return);
            }
            //$has['access_token'] = $this->authcode($has['id'], 'jiami');
            session('member_id',$has['id']);
            session('memberInfo',$has);
            $return['code'] = 200;
            $return['msg'] = '登录成功';
            //$return['data'] = $has;
            return json($return);
        }

        return $this->fetch('login');
    }


    public function seller_login(){
        if ($this->request->isAjax()) {
            $return = $this->return;
            $tel = input("param.tel", 0);
            if (empty($tel)) {
                $return['msg'] = '手机号不能为空';
                return json($return);
            }

            if (!check_tel($tel)) {
                $return['msg'] = '手机号格式不正确';
                return json($return);
            }
            $has = Member::getOne(['tel'=>$tel]);

            if (empty($has)) {
                $return['msg'] = '该手机号用户不存在';
                return json($return);
            }

            $password = input('password');
            if (!$password) {
                $return['msg'] = '密码不能为空';
                return json($return);
            }

            if ($has['password'] !== md5(md5($password))) {
                $return['msg'] = '密码不正确';
                return json($return);
            }
            //$has['access_token'] = $this->authcode($has['id'], 'jiami');
            session('member_id',$has['id']);
            session('memberInfo',$has);
            $return['code'] = 200;
            $return['msg'] = '登录成功';
            //$return['data'] = $has;
            return json($return);
        }

        return $this->fetch('seller_login');
    }

    /**
     * 退出登陆
     */
    public function logout()
    {
        Session::delete('member_id');
        Session::delete('memberInfo');
        $this->redirect(url('index/index/index')->build());
    }


    public function register(){
        if($this->request->isAjax()){
            $return = $this->return;
            $tel = input("param.tel", 0);
            if (empty($tel)) {
                $return['msg'] = '手机号不能为空';
                return json($return);
            }

            if (!check_tel($tel)) {
                $return['msg'] = '手机号格式不正确';
                return json($return);
            }

            $has = Member::getOne(['tel'=>$tel]);

            if (!empty($has)) {
                $return['msg'] = '该手机号码已经注册';
                return json($return);
            }

            $insert['user_name'] = $tel;
            $insert['tel'] = $tel;
            $insert['create_time'] = time();
            $password = input('password');
            if (!$password) {
                $return['msg'] = '密码不能为空';
                return json($return);
            }

            if (strlen($password) < 6) {
                $return['msg'] = '密码长度不能低于6位';
                return json($return);
            }

            $insert['password'] = md5(md5($password));
            $code = input('param.code');
            if (!$code) {
                $return['msg'] = '验证码不能为空';
                return json($return);
            }

            $count = Db::name('email_code')->where(['tel' => $tel, 'code' => $code])->count();
            if ($count == 0) {
                $return['msg'] = '验证码错误,请重新发送';
                return json($return);
            }


            $res = Member::create($insert);

            $return['code'] = 200;
            $return['msg'] = '注册成功';
            return json($return);
        }
        return $this->fetch('register');
    }


    public function checkRegisterUser(){
        $return  = $this->return;

        $type = input('param.type');

        $tel = input("param.tel",0);
        if(empty($tel)){
            $return['msg'] = '手机号不能为空';
            return json($return);
        }

        if(!check_tel($tel)){
            $return['msg'] = '手机号格式不正确';
            return json($return);
        }

        $has = MemberModel::getOne(['tel'=>$tel]);

        if(!empty($has)){
            $return['msg'] = '该手机号码已经注册';
            return json($return);
        }

        $return['code'] = 200;
        $return['msg'] = '请求成功';
        return json($return);
    }

    //发送短信
    public function sendCode(){

        $return  = $this->return;

        $arr = [
            1=>'SMS_174277436', //注册
            2=>'SMS_174580823',//免密登录
            3=>'SMS_174272354', //重置密码
        ];

        $type = input('param.type',1);

        $tel = input("param.tel",0);
        if(empty($tel)){
            $return['msg'] = '手机号不能为空';
            return json($return);
        }

        if(!check_tel($tel)){
            $return['msg'] = '手机号格式正确';
            return json($return);
        }

        /*
        $has = $this->checkHasTel($tel);

        if(!empty($has)){
            $return['msg'] = '该手机号码已经注册';
            return json($return);
        }
        */

        $code = '';
        // $db = Db::name('email_code');
        //$has = $db->where(['tel'=>$tel])->find();
        //if(!empty($has)){
        //    $code = $has['code'];
        //}else{

        $code = randString();
        $sql = "REPLACE INTO ptf_email_code (`code`,tel) VALUES ('$code','$tel')";
        Db::execute($sql);
        //}

        $res = $this->apiSms($tel,$code,$arr[$type]);
        if($res['code'] !=200){
            $return['msg'] = $res['msg'];
            return json($return);
        }

        $return['code'] = 200;
        $return['msg'] = '发送成功';
        $return['data'] = $code;

        return json($return);
    }

    public function apiSms($tel,$code,$tpl = 'SMS_174277436'){

        $return = $this->return;
        // Download：https://github.com/aliyun/openapi-sdk-php
        // Usage：https://github.com/aliyun/openapi-sdk-php/blob/master/README.md
        $accessKeyId = 'LTAI56Cm4nCIGZas';
        $accessSecret = 'tSBMN3eGNLOqnhXgxahUeXUwCYtJL2';
        AlibabaCloud::accessKeyClient($accessKeyId,$accessSecret)
            ->regionId('234')
            ->asDefaultClient();

        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "234",
                        'PhoneNumbers' => $tel,
                        'SignName' => "九五科技",
                        'TemplateCode' => $tpl,
                        'TemplateParam' => "{code:'$code'}",
                    ],
                ])
                ->request();

            if($result->Code == 'OK' || $result->Code == 'isv.BUSINESS_LIMIT_CONTROL'){
                $return['code'] = 200;
            }


        } catch (ClientException $e) {
            $return['msg'] = $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            $return['msg'] = $e->getErrorMessage() . PHP_EOL;
        }

        return $return;
    }
}